<?php

namespace Account\Model;

use Common\Model\BaseModel;
use Common\Model\ModelException;

/**
 * 关注
 */
class UserFavoriteModel extends BaseModel {

    protected $_auto = [
        ['create_time', 'time', self::MODEL_INSERT, 'function'],
    ];
    protected $_validate = [
        ['user_id', 'require', '关注人的ID不能为空'],
        ['to_user_id', 'require', '关注对象的ID不能为空'],
    ];
    protected $_scope = [
    ];

    /**
     * 添加关注人，若已关注则略过，不验证不存在的用户
     * @param integer $from 发起人
     * @param array  $tos  要关注的人
     */
    public function addFavorites($from, array $tos) {
        $existedUids = D('UserFavorite')->where(['user_id' => $from])->getField('to_user_id', true);
        $existedUids = $existedUids ? : [];
        $uids = array_diff($tos, $existedUids);
        $fromUser = D('Users')->find($from);
        foreach ($uids as $uid) {
            $data = [
                'user_id' => $from,
                'to_user_id' => $uid,
                'create_time'=>time()
            ];
            $favoriteModel = D('UserFavorite');
            if ($favoriteModel->create($data)) {
                $favoriteModel->add();
                /* 粉丝数 关注数 + 1 */
                D('Users')->where(['user_id' => $from])->setInc('following_count');
                D('Users')->where(['user_id' => $uid])->setInc('followers_count');
                if (!C('sdk.jpush')) {
                    $toUser = D('Users')->find($uid);
                    D('Helper/Notification')->following($fromUser, $toUser);
                }
            } else {
                throw new ModelException(40000, $favoriteModel->getError());
            }
        }
        return true;
    }

    public function delFans($from, $to) {
        $isExist = D('UserFavorite')->where(['user_id' => $from, 'to_user_id' => $to])->find();
        if ($isExist) {
            D('UserFavorite')->where(['user_id' => $from, 'to_user_id' => $to])->delete();
            D('Users')->where(['user_id' => $from])->setDec('following_count');
            D('Users')->where(['user_id' => $to])->setDec('followers_count');
            return true;
        } else {
            $this->error = '未关注该用户';
            $this->errorCode = 40002;
            return false;
        }
    }

    /**
     * 填充关注状态
     * @param  [type] $uid   [description]
     * @param  [type] $users [description]
     * @return [type]        [description]
     */
    public function fill($uid, &$users) {
        $favoriteIds = D('UserFavorite')->where(['user_id' => $uid])->getField('to_user_id', true);
        foreach ($users as &$user) {
            $user['is_like'] = in_array($user['id'], $favoriteIds);
        }
    }

}
